<template>
    <div>
        <van-nav-bar :title="route.meta.title" left-arrow @click-left="router.back()" fixed placeholder />
        <van-address-edit :area-list="areaList" :area-columns-placeholder="['请选择', '请选择', '请选择']" show-delete
            show-set-default show-search-result :address-info="adressList" @save="onSave" @delete="onDelete" />
    </div>
</template>
    
<script setup>
import { useRoute, useRouter } from 'vue-router';
import { areaList } from '@vant/area-data';
import { useAddressStore } from '@/stores/address.js'
import { addAddress, updateAddress, deleteAddress } from '@/api/address.js'
import { onMounted, ref, inject } from 'vue'
import { showSuccessToast } from 'vant';
const router = useRouter()
const route = useRoute()
const addressStore = useAddressStore()

//地址信息回显的容器
let adressList = ref({})
let isEdit = ref(false)
let addressId = ref('')
//刷新页面方法
let reload = inject('reload')
onMounted(() => {
    if (route.query.data) {
        isEdit.value = true
        let res = JSON.parse(decodeURI(atob(route.query.data)))
        adressList.value.name = res.name
        adressList.value.tel = res.phone
        adressList.value.province = res.province
        adressList.value.city = res.city
        adressList.value.county = res.town
        adressList.value.addressDetail = res.detail
        /* adressList.value.areaCode='' */
        adressList.value.isDefault = res.is_default == 1 ? true : false
        addressId.value = res.id

    }
})

let onSave = async (res) => {
    if (res.isDefault == true) {
        addressStore.setAddressInfo()
    }
    if (isEdit.value) {
        await updateAddress({
            id: addressId.value,
            is_default: res.isDefault == true ? '1' : '0',
            name: res.name,
            phone: res.tel,
            province: res.province,
            city: res.city,
            town: res.county,
            street: 'null',
            detail: res.addressDetail,
        })
        showSuccessToast({
            message: '修改成功',
            duration: 1500,
        });
    } else {
        await addAddress({
            is_default: res.isDefault == true ? '1' : '0',
            name: res.name,
            phone: res.tel,
            province: res.province,
            city: res.city,
            town: res.county,
            street: 'null',
            detail: res.addressDetail,
        })

    }
    router.push({ name: 'address' })
    reload()
}
let onDelete = async () => {
    await deleteAddress({
        id: addressId.value
    })
    router.push({ name: 'address' })
    reload()
}

</script>
    
<style  scoped></style>